package com.util;

import lombok.Data;
import lombok.Getter;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

@Data
public class CollectorsDemo {

    /**
     * 将对象根据某个列做distinct
     */
    @Test
    public void testToMap(){
        List<ColDemo> list = new ArrayList();
        list.add(new ColDemo(1, "YLw", "so beautify"));
        list.add(new ColDemo(2, "YTt", "so fat"));
        list.add(new ColDemo(1, "YTt", "so beautify"));

        //当id重复时报错
//        Map<Integer, ColDemo> s = list.stream().collect(Collectors.`toMap`(CsolDemo::getId, t -> t));
//        System.out.println(s);
        //当key重复时保留原有的
        Map<Integer, ColDemo> s1 = list.stream().collect(Collectors.toMap(k->k.id, t -> t, (existing, replacement) -> existing, LinkedHashMap::new));
        System.out.println(s1);
    }

    /**
     * groupingBy
     */
    @Test
    public void testGroupingBy() {
        List<Integer> list = new ArrayList() {
            {
                add(12);
                add(20);
                add(12);
                add(22);
                add(22);
                add(23);
                add(159);
                add(12);
            }
        };

        Map<Integer, Long> map = list.stream().collect(
                Collectors.groupingBy(p -> p, Collectors.counting())
        );

        map.forEach((k, v) -> System.out.println(k + ":" + v));
        System.out.println("---------------");
         map = list.stream().collect(
                Collectors.groupingBy(p -> p, Collectors.summingLong(Long::new))
        );
        map.forEach((k, v) -> System.out.println(k + ":" + v));

    }
}
@Data
@Getter
class ColDemo{
    Integer id;
    String name;
    String value;

    public ColDemo(Integer id, String name, String value) {
        this.id = id;
        this.name = name;
        this.value = value;
    }
}
